//
//  CTReverseViewController.swift
//  mggz
//
//  Created by QinWei on 2018/3/12.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class CTReverseViewController: UIViewController {

    @IBOutlet weak var headerButton: UIButton!
    var informationArray:NSMutableArray?
    var backInfoArray:NSMutableArray?
    var headerImage:UIImage?
    var backCardImage:UIImage?
    var positiveCardImage:UIImage?
    var startTime:String?
    var endTime:String?
    var timeAlert:TWLAlertView?
    
  //  @IBOutlet weak var headerView: UIImageView!
    
    @IBOutlet weak var bottomView: UIView!
    
    @IBOutlet weak var legalDate: UILabel!
    
    @IBOutlet weak var idCardView: UIImageView!
    
    
    @IBOutlet weak var applicationButton: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.headerButton.setImage(self.headerImage, for: .normal)
        self.headerButton.isEnabled = false
        self.headerButton.layer.cornerRadius = 52
        self.headerButton.layer.masksToBounds = true
        
        
        self.idCardView.layer.cornerRadius = 5
        self.idCardView.layer.masksToBounds = true
        
        self.applicationButton.layer.cornerRadius = 5
        self.applicationButton.layer.masksToBounds = true
        
        AipOcrService.shard().auth(withAK: BaiduYunAPIKey, andSK: BaiduYunSecretKey)
        let tap = UITapGestureRecognizer(target: self, action: #selector(idCardButtonClick(_:)))
        self.bottomView.addGestureRecognizer(tap)
    }
    @objc func idCardButtonClick(_ sender: UITapGestureRecognizer) {
        
        let ocrVc = AipCaptureCardVC.viewController(with: .localIdCardBack) { (ocrImage) in
            AipOcrService.shard().detectIdCardBack(from: ocrImage, withOptions: nil, successHandler: { (result) in
                DispatchQueue.main.async {
                     self.setupResultWithUI(result as! [String : AnyObject])
                    self.dismiss(animated: true, completion: {
                        
                    })
                    // self.idImageView.image = ocrImage
                    // self.scanImage = ocrImage
                    self.idCardView.image = ocrImage
                    self.backCardImage = ocrImage
                    
                }
            }, failHandler: { (error) in
                
            })
        }
        
        self.present(ocrVc!, animated: true) {
            
        }
        
    }
    
    fileprivate func setupResultWithUI(_ result:[String:AnyObject]){
       
        self.backInfoArray = NSMutableArray.init()
        if (result["words_result"] != nil){
            (result["words_result"])?.enumerateKeysAndObjects({ (mykey, myObj, myStop) in
                guard let selectObj : NSDictionary = myObj as? NSDictionary else{
                    return
                }
                if let selectWord = selectObj["words"] {
                    self.backInfoArray?.add(selectWord)
                    
                }else{
                    return
                }
            })
        }else{
            
        }
        
        
        self.dealWithTime(self.backInfoArray!)
        
}
    fileprivate func dealWithTime(_ backArray:NSMutableArray){
        
        guard var firstTime = backArray[1] as? String else {
            return
        }
        guard var secondTime = backArray[0] as? String else {
            return
        }
        
        
        firstTime.insert("-", at: (firstTime.index((firstTime.startIndex), offsetBy: 4)))
        
        firstTime.insert("-", at: (firstTime.index((firstTime.startIndex), offsetBy: 7)))
        if secondTime.count > 7 {
            
        secondTime.insert("-", at: (secondTime.index((secondTime.startIndex), offsetBy: 4)))
        secondTime.insert("-", at: (secondTime.index((secondTime.startIndex), offsetBy: 7)))
            
        }
        self.startTime = firstTime
        self.endTime = secondTime
        self.legalDate.text = firstTime + "至" + secondTime
    }
    @IBAction func applicationButtonClick(_ sender: Any) {
        guard (self.backCardImage != nil) else {
            QWTextonlyHud("身份证反面未扫描", target: self.view)
            return
        }
        guard (self.startTime != "") else {
            QWTextonlyHud("数据不完整", target: self.view)
            return
        }
        guard (self.endTime != "") else {
            QWTextonlyHud("数据不完整", target: self.view)
            return
        }
        if (self.endTime?.count)! > Int(8){
            let cardDate = stringToDate(dateString: self.endTime!)
            if cardDate! < Date(){
                QWTextonlyHud("身份证已过期，请拍摄有效的身份证", target: self.view)
                return
            }
        }
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let custom : CTApplicationView = CTApplicationView.init(frame: CGRect(x: 0, y: 0, width: 250, height: 130))
        custom.applicationButton.addTarget(self, action: #selector(applicationAllInfoClick), for: .touchUpInside)
        custom.cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
        self.timeAlert?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 250, height: 130))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeAlert!)
    }
    
    @objc fileprivate func applicationAllInfoClick(){
       self.timeAlert?.cancleView()
        
        var avatarModel: ImageUploadModel?
        var idPhotoModels = [ImageUploadModel]()
        var guid: String?
        var orderNo: String?
        
        
        let dispatchGroup = DispatchGroup()
        
        dispatchGroup.enter()
        //上传头像
        ImageUploadModel.commitImage([self.headerImage!]) { (response) in
            if response.success {
                avatarModel = response.value![0]
            }
            else {
                WWError(response.message)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        ImageUploadModel.commitImage([self.positiveCardImage!,self.backCardImage!],isCertification: true) { (response) in
            if response.success {
                idPhotoModels = response.value!
            }
            else
            {
                WWError(response.message)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else {
                WWError("guid获取失败")
            }
            dispatchGroup.leave()
        }
        
        let orderConfigId = "57ed0987-1c79-4c67-b6f8-23ec6304ba38"
      
        
      UserModel.getOrderNo(orderConfigId: orderConfigId) { (response) in
            if response.success {
                orderNo = response.value
            }
            else {
                WWError("获取orderNo出错")
            }
        }
        
        dispatchGroup.notify(queue: DispatchQueue.main) {
            
            WWBeginLoadingWithStatus("开始认证")
            
            guard avatarModel != nil  else{
                WWError("头像上传出错")
                return
            }
            
            guard idPhotoModels.count == 2 else {
                WWError("身份证照上传出错")
                return
            }
            guard guid != nil else {
                return
            }
            guard orderNo != nil else {
                return
            }
            
            guard let userName = self.informationArray![0] as? String else {
                return
            }
            guard let userCardId = self.informationArray![2] as? String else {
                return
            }
            guard let userSex = self.informationArray![3] as? String else {
                return
            }
            guard let userAddress = self.informationArray![4] as? String else {
                return
            }
            
            self.submitCertificaiton(guid!, orderNo: orderNo!, name: userName, sex: userSex == "男" ? 0 : 1, iDCard: userCardId, userAddress: userAddress, startTime: self.startTime!, endTime: self.endTime!, avatar:  avatarModel!, idPhotos: idPhotoModels)
     }
}
    
    //提交认证
    func submitCertificaiton(_ guid: String, orderNo: String, name: String, sex: Int, iDCard: String, userAddress: String,startTime:String,endTime:String, avatar:ImageUploadModel, idPhotos:[ImageUploadModel]) {
    
        CertificationModel.submitCertificationInfo(guid, orderNo: orderNo, name: name, sex: sex, iDCard: iDCard, userAdress: userAddress, startTime: startTime, endTime: endTime, avatar: avatar, idPhotos: idPhotos, operate: "1") { (reponse) in
            if reponse.success {
                WWSuccess("成功")
                self.present(WWTabBarController(), animated: true, completion: nil)
                self.checkCertificationStatus()
            }
            else
            {
                WWError(reponse.message)
            }
        }
}

    private func checkCertificationStatus() {
        CertificationModel.checkCertificationStatus({ (response) in
            if response.success {
            //WWUser.sharedInstance.ensureCertificationStatus(self)
            }
            else {
            }
        })
    }
    @objc fileprivate func cancelButtonClick(){
        self.timeAlert?.cancleView()
    }    
}
